
import { compare, getReal } from '../common.js'
export default class Rect {

  constructor(ctx){
    this.Ctx = ctx;
  }

  // 绘制矩形
  rect(info, save = true,reload = true, resolve = () => {}) {
    this.Ctx.ctx.save()
    if(info.auxProps) {
      for(let [k, v] of Object.entries(info.auxProps)) {
        this.Ctx.ctx[k] = v;
      }
    }
    let {x, y,id = new Date().getTime(), width = 10,height = 10,rotate = 0,lineWidth, textInfo, fillColor, fillType='stroke', level = 1, type = 'rect'} = info;
    if(reload) {
      this.Ctx.repaint();
    }
    let ele = {};
    this.Ctx.rotate = rotate;
    let startX = 0;
    let startY = 0;
    let originX = 0;
    let originY = 0;
    this.Ctx.ctx.lineWidth = lineWidth || 1;
    this.Ctx.Custom.setColor({fillColor, fillType})
    if(this.Ctx.ele && id === this.Ctx.ele.id){
      originX = this.Ctx.originX;
      originY = this.Ctx.originY;
      startX = this.Ctx.dragStartX+this.Ctx.subX;
      startY = this.Ctx.dragStartY+this.Ctx.subY;
    }else{
      originX = x+width/2;
      originY = y+height/2;
      startX = -width/2;
      startY = -height/2;
    }
    this.Ctx.setStore(this.Ctx.ctx, {rotate, originX, originY}, () => {
      if(fillType === 'stroke'){
        this.Ctx.ctx.strokeRect(startX, startY, width, height);  // 此处不用xy作为原点直接绘制，当前坐标系原点已被重新定义
      }else{
        this.Ctx.ctx.fillRect(startX, startY, width, height);
      }
    })
    if(type === 'image') this.Ctx.loadImage(info, {startX, startY, originX, originY}, resolve)   // 图片仍然通过绘制矩形的方法绘制，保留一切矩形的原有属性
    let copyX = x;
    let copyY = y;
    if(save) {
      if(this.Ctx.ele && id === this.Ctx.ele.id){
        // 移动前的中心点 this.Ctx.startCenterX/this.Ctx.startCenterY
        // 移动后的中心点 x+width/2 / y+height/2
        // 移动前的虚拟坐标 this.Ctx.startCenterX - (x+width/2), this.Ctx.startCenterY - (y+height/2)
        let {realX,realY} = getReal({x:this.Ctx.startCenterX - (x+width/2), y: this.Ctx.startCenterY - (y+height/2),rotate:-rotate});
        let subX = (this.Ctx.startCenterX - (x+width/2)) - realX;
        let subY = (this.Ctx.startCenterY - (y+height/2)) - realY;
        copyX += subX;
        copyY += subY;
      }
      let x1 = copyX;
      let y1 = copyY;
      let x2 = copyX + width;
      let y2 = copyY + height;
      let obj = compare([[x1,x2],[y1,y2]]);
      ele = Object.assign({...info, id,type,x:copyX,y:copyY,width,height,endX:0,endY:0,rotate,textInfo,fillColor,fillType,lineWidth,level},obj)
      this.Ctx.canvasInfoMap.set(ele.id, ele)
    }
    this.Ctx.ctx.restore()
    if(save) return ele
  }
}